package com.wkbb.sports.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.wkbb.common.dto.basic.*;
import com.wkbb.sports.dto.*;
import com.wkbb.sports.enums.SportsModelTypeEnum;
import com.wkbb.sports.mapper.BasicMapper;
import com.wkbb.sports.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.sports.enums.SportsProjectKindEnum;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.model.HlifeOrgGrade;
import com.wkbb.sports.service.RuleService;
import com.wkbb.sports.service.StatisticsService;
import com.wkbb.sports.service.TrainService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

@RestController
@Api(description = "pc端训练报表")
@RequestMapping("/sports/{apiVersion}/pcstatistics")
@Slf4j
public class PCStatisticsController {
	
	@Autowired
	private TrainService trainService;
	@Autowired
	private StatisticsService statisticsService;
	@Autowired
	private RuleService ruleService;
    @Autowired
    private BasicFeignService basicFeignService;
	@Autowired
	BasicMapper basicMapper;

	@ApiOperation(value = "获取可选城市列表")
	@RequestMapping(value = "/getCityListByOrg", method = RequestMethod.GET)
	public ResultDTO<List<DistrictDto>> getCityListByOrg(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion)throws Exception{
		List<DistrictDto> list = statisticsService.getCityListByOrg();
		DistrictDto districtDto = new DistrictDto();
		districtDto.setCode(0);
		districtDto.setName("全区");
		list.add(0,districtDto);
		return new ResultDTO<>(list);
	}

	@ApiOperation(value = "获取大数据中心数据")
	@RequestMapping(value = "/getBCDTBasic", method = RequestMethod.GET)
	public ResultDTO<BCDTBasicDto> getBCDTBasic(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "城市ID", required = true, defaultValue = "0") @RequestParam(name = "cityID", required = false) Integer cityID)throws Exception{
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("cityID", cityID);
		BCDTBasicDto dto = statisticsService.getBCDTBasic(params);
		return new ResultDTO<>(dto);
	}

	@ApiOperation(value = "获取大数据中心数据")
	@RequestMapping(value = "/getBCDT", method = RequestMethod.GET)
	public ResultDTO<BCDTDto> getBCDT(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "城市ID", required = true, defaultValue = "0") @RequestParam(name = "cityID", required = false) Integer cityID,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "beginDate", required = false) String beginDate,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endDate", required = false) String endDate)throws Exception{
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("cityID", cityID);
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		BCDTDto dto = statisticsService.getBCDT(params);
		return new ResultDTO<>(dto);
	}

	@ApiOperation(value = "获取大数据中心项目数据")
	@RequestMapping(value = "/getBCDTByKind", method = RequestMethod.GET)
	public ResultDTO<BCDTKindDto> getBCDTByKind(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "城市ID", required = true, defaultValue = "0") @RequestParam(name = "cityID", required = false) Integer cityID,
			@ApiParam(value = "项目ID", required = true, defaultValue = "1") @RequestParam(name = "projectKind", required = false) Integer projectKind,
			@ApiParam(value = "项目ID", required = true, defaultValue = "1") @RequestParam(name = "modelType", required = false) Integer modelType,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "beginDate", required = false) String beginDate,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endDate", required = false) String endDate)throws Exception{
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("cityID", cityID);
		params.put("beginDate", beginDate);
		params.put("projectKind", projectKind);
		params.put("modelType", modelType);
		params.put("endDate", endDate);
		params.put("yesterday", DateUtil.addCurrDay(-1));
		BCDTKindDto dto = statisticsService.getBCDTByKind(params);
		return new ResultDTO<>(dto);
	}

	@ApiOperation(value = "获取实时项目列表")
	@RequestMapping(value = "/getNowBCDTByKind", method = RequestMethod.GET)
	public ResultDTO<BCDTNowKindDto> getBCDTByKind(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "城市ID", required = true, defaultValue = "0") @RequestParam(name = "cityID", required = false) Integer cityID,
			@ApiParam(value = "项目ID", required = true, defaultValue = "1") @RequestParam(name = "modelType", required = false) Integer modelType,
			@ApiParam(value = "项目ID", required = true, defaultValue = "1") @RequestParam(name = "projectKind", required = false) Integer projectKind)throws Exception{
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("cityID", cityID);
		params.put("projectKind", projectKind);
		params.put("modelType", modelType);
		//1小时内 心率异常 实时参与人数
		params.put("beginDate", DateUtil.addCurrMinute(-60));
		params.put("endDate", DateUtil.getDateTime());
		BCDTNowKindDto dto = statisticsService.getNowBCDTByKind(params);
		return new ResultDTO<>(dto);
	}

	@ApiOperation(value = "训练首页")
	@RequestMapping(value = "/getTrainHomePage", method = RequestMethod.GET)
	public ResultDTO<TrainAnalysisDto> getTrainHomePage(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId)throws Exception{
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		TrainAnalysisDto trainAnalysisDto = statisticsService.getTrainHomePage(params);
		return new ResultDTO<>(trainAnalysisDto);
	}

	@ApiOperation(value = "训练首页-项目数据")
	@RequestMapping(value = "/getTrainHomePageKind", method = RequestMethod.GET)
	public ResultDTO<TrainAnalysisDto> getTrainHomePageKind(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "项目ID", required = true) @RequestParam(name = "projectKind", required = true) Long projectKind,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "beginDate", required = false) String beginDate,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endDate", required = false) String endDate)throws Exception{
		Map<String, Object> params = new HashMap<>();
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		params.put("orgId", orgId);
		params.put("projectKind", projectKind);
		TrainAnalysisDto trainAnalysisDto = statisticsService.getTrainHomePageKind(params);
		return new ResultDTO<>(trainAnalysisDto);
	}

	@ApiOperation(value = "训练首页")
	@RequestMapping(value = "/getTrainFirstPage", method = RequestMethod.GET)
	public ResultDTO<?> getTrainFirstPage(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "beginTime", required = false) String beginTime,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endTime", required = false) String endTime)throws Exception{
		Map<String, Object> result = new HashMap<>();
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> params = new HashMap<>();
		params.put("beginTime", df.format(df.parse(beginTime + " 00:01:01")));
		params.put("endTime", df.format(df.parse(endTime + " 23:59:59")));
		params.put("orgId", orgId);
		
		String trianIds;
		try{
			trianIds = statisticsService.getTrainIds(params);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		
		if(trianIds == null || "".equals(trianIds)) {
			return new ResultDTO<>(result);
		}
		
		List<HlifeOrgGrade> orgGrades = ruleService.queryOrgGradeList(orgId);

		List<JumpGradeSummaryDto> summaryList = null;
		try{
			summaryList = statisticsService.queryTrainGradeSummaryList(trianIds);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		
		List<ProjectAverageDto> projectAverages = statisticsService.queryProjectAverageList(trianIds);
		result.put("descriptions", buildProjectDescriptions(summaryList));
		result.put("pieGraph", buildPieGraph(summaryList));
		result.put("gradeNames", buildGradeNames(summaryList, orgGrades));
		result.put("gradeDesc", buildGradeDescriptions(summaryList));
		result.put("gradeBarGraph", buildGradeBarGraph(summaryList));
		result.put("barGraph", buildBarGraph(projectAverages));
		result.put("radarGraph", buildRarGraph(projectAverages));
		result.put("trainCount", trianIds.split(",").length);
		
		return new ResultDTO<>(result);
	}
	
	
	private List<ProjectBarDto> buildBarGraph(List<ProjectAverageDto> projectAverages) {
		ProjectBarDto speed = new ProjectBarDto("速度", "长跑平均速度（s）", "train_speed", "train1.png");
		ProjectBarDto coordinate = new ProjectBarDto("协调", "跳绳平均个数（个）", "train_coordinate", "train2.png");
		for(ProjectAverageDto projectAverage : projectAverages) {
			if(projectAverage.getProjectKind() == SportsProjectKindEnum.ROPESKIPPING.getValue().byteValue()) {
				coordinate.add(projectAverage.getTotal(), projectAverage.getTotalScore());
			}else if(projectAverage.getProjectKind() == SportsProjectKindEnum.RUNNING.getValue().byteValue()) {
				speed.add(projectAverage.getTotal(), projectAverage.getTotalScore());
			}
		}
		List<ProjectBarDto> list = new ArrayList<>();
		list.add(speed);
		list.add(coordinate);
		return list;
	}
	
	
	private List<ProjectRadarDto> buildRarGraph(List<ProjectAverageDto> projectAverages) {
		ProjectRadarDto speed = new ProjectRadarDto("速度");
		ProjectRadarDto coordinate = new ProjectRadarDto("协调");
		for(ProjectAverageDto projectAverage : projectAverages) {
			if(projectAverage.getProjectKind() == SportsProjectKindEnum.ROPESKIPPING.getValue().byteValue()) {
				coordinate.add(projectAverage.getTotal(), projectAverage.getTotalScore());
			}else if(projectAverage.getProjectKind() == SportsProjectKindEnum.RUNNING.getValue().byteValue()) {
				speed.add(projectAverage.getTotal(), projectAverage.getTotalScore());
			}
		}
		List<ProjectRadarDto> list = new ArrayList<>();
		list.add(speed);
		list.add(coordinate);
		return list;
	}


	@ApiOperation(value = "协调及速度首页")
	@RequestMapping(value = "/getProjectFirstPage", method = RequestMethod.GET)
	public ResultDTO<?> getProjectFirstPage(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "项目类型", required = false) @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "模式", required = false) @RequestParam(name = "modelType", required = false) Byte modelType,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "startTime", required = false) String beginTime,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endTime", required = false) String endTime)throws Exception{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> params = new HashMap<>();
		params.put("beginTime", df.format(df.parse(beginTime + " 00:01:01")));
		params.put("endTime", df.format(df.parse(endTime + " 23:59:59")));
		params.put("projectKind", projectKind);
		params.put("modelType", modelType);
		params.put("orgId", orgId);
		
		String trianIds;
		try{
			trianIds = statisticsService.getTrainIds(params);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		
		List<HlifeOrgGrade> orgGrades = ruleService.queryOrgGradeList(orgId);

		List<JumpGradeSummaryDto> summaryList = null;
		try{
			summaryList = statisticsService.queryTrainGradeSummaryList(trianIds);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		
		Map<String, Object> result = new HashMap<>();
		
		result.put("descriptions", buildProjectDescriptions(summaryList));
		result.put("pieGraph", buildPieGraph(summaryList));
		result.put("gradeNames", buildGradeNames(summaryList, orgGrades));
		result.put("gradeDesc", buildGradeDescriptions(summaryList));
		result.put("gradeBarGraph", buildGradeBarGraph(summaryList));
		result.put("trainCount", trianIds.split(",").length);
		
		ProjectOrgAverageDto average = null;
		
		try {
			average = statisticsService.getOrgAverage(trianIds);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		
		result.put("average", average);
		
		return new ResultDTO<>(result);
	}

	private List<ProjectTrainDescriptionDto> buildProjectDescriptions(List<JumpGradeSummaryDto> summaryList) {
		ProjectTrainDescriptionDto fine = new ProjectTrainDescriptionDto(3, "优秀", "#0FDD8D");
		ProjectTrainDescriptionDto good = new ProjectTrainDescriptionDto(2, "良好", "#62F0FB");
		ProjectTrainDescriptionDto pass = new ProjectTrainDescriptionDto(1, "及格", "#FFD02E");
		int total = 0;
		for(JumpGradeSummaryDto gradeSummary : summaryList) {
			fine.setNan(fine.getNan() + gradeSummary.getMaleFine());
			fine.setNv(fine.getNv() + gradeSummary.getFemaleFine());
			good.setNan(good.getNan() + gradeSummary.getMaleGood());
			good.setNv(good.getNv() + gradeSummary.getFemaleGood());
			pass.setNan(pass.getNan() + gradeSummary.getMalePass());
			pass.setNv(pass.getNv() + gradeSummary.getFemalePass());
			total += gradeSummary.getFemaleTotal() + gradeSummary.getMaleTotal();
		}
		fine.buildNum(total);
		good.buildNum(total);
		pass.buildNum(total);
		List<ProjectTrainDescriptionDto> list = new ArrayList<>();
		list.add(fine);
		list.add(good);
		list.add(pass);
		return list;
	}

	private List<ProjectTrainPieGraph> buildPieGraph(List<JumpGradeSummaryDto> summaryList) {
		ProjectTrainPieGraph fine = new ProjectTrainPieGraph(3, "优秀");
		ProjectTrainPieGraph good = new ProjectTrainPieGraph(2, "良好");
		ProjectTrainPieGraph pass = new ProjectTrainPieGraph(1, "及格");
		for(JumpGradeSummaryDto gradeSummary : summaryList) {
			fine.setValue(fine.getValue() + gradeSummary.getFine());
			good.setValue(good.getValue() + gradeSummary.getGood());
			pass.setValue(pass.getValue() + gradeSummary.getPass());
		}
		List<ProjectTrainPieGraph> list = new ArrayList<>();
		list.add(fine);
		list.add(good);
		list.add(pass);
		return list;
	}
	
	private static String[] gradeNames = new String[] {
			"一年级","二年级","三年级","四年级","五年级","六年级","七年级","八年级","九年级","十年级","十一年级","十二年级"
	};

	private List<String> buildGradeNames(List<JumpGradeSummaryDto> summaryList, List<HlifeOrgGrade> orgGrades) {
		List<String> list = new ArrayList<>();
		for(JumpGradeSummaryDto gradeSummary : summaryList) {
			long gradeId = gradeSummary.getGradeId();
			for(HlifeOrgGrade orgGrade : orgGrades) {
				if(gradeId == orgGrade.getGradeId()) {
					int level = (int)(orgGrade.getRuleGradeId() - 40);
					list.add(gradeNames[level]);
				}
			}
		}
		return list;
	}

	private List<ProjectGradeDescriptionDto> buildGradeDescriptions(List<JumpGradeSummaryDto> summaryList) {
		ProjectGradeDescriptionDto fine = new ProjectGradeDescriptionDto(1, "优秀", "#0FDD8D");
		ProjectGradeDescriptionDto good = new ProjectGradeDescriptionDto(2, "良好", "#62F0FB");
		ProjectGradeDescriptionDto pass = new ProjectGradeDescriptionDto(3, "及格", "#FFD02E");
		ProjectGradeDescriptionDto fail = new ProjectGradeDescriptionDto(4, "不及格", "#FDE08C");
		List<ProjectGradeDescriptionDto> list = new ArrayList<>();
		int total = 0;
		for(JumpGradeSummaryDto gradeSummary : summaryList) {
			fine.setTotal(fine.getTotal() + gradeSummary.getFine());
			good.setTotal(good.getTotal() + gradeSummary.getGood());
			pass.setTotal(pass.getTotal() + gradeSummary.getPass());
			fail.setTotal(fail.getTotal() + gradeSummary.getFail());
			total += gradeSummary.getMaleTotal() + gradeSummary.getFemaleTotal();
		}
		fine.buildNum(total);
		good.buildNum(total);
		pass.buildNum(total);
		fail.buildNum(total);
		list.add(fine);
		list.add(good);
		list.add(pass);
		list.add(fail);
		return list;
	}

	private List<ProjectGradeBarGraph> buildGradeBarGraph(List<JumpGradeSummaryDto> summaryList) {
		ProjectGradeBarGraph fine = new ProjectGradeBarGraph(1, "优秀");
		ProjectGradeBarGraph good = new ProjectGradeBarGraph(2, "良好");
		ProjectGradeBarGraph pass = new ProjectGradeBarGraph(3, "及格");
		ProjectGradeBarGraph fail = new ProjectGradeBarGraph(4, "不及格");
		for(JumpGradeSummaryDto gradeSummary : summaryList) {
			fine.addData(gradeSummary.getFine());
			good.addData(gradeSummary.getGood());
			pass.addData(gradeSummary.getPass());
			fail.addData(gradeSummary.getFail());
		}
		List<ProjectGradeBarGraph> list = new ArrayList<>();
		list.add(fine);
		list.add(good);
		list.add(pass);
		list.add(fail);
		return list;
	}
	
	@ApiOperation(value = "协调及速度首页-选择年级")
	@RequestMapping(value = "/getProjectFirstPageSelectGrade", method = RequestMethod.GET)
	public ResultDTO<?> getProjectFirstPageSelectGrade(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "项目类型", required = false) @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "模式", required = false) @RequestParam(name = "modelType", required = false) Byte modelType,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "startTime", required = false) String beginTime,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endTime", required = false) String endTime,
			@ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId)throws Exception{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> params = new HashMap<>();
		params.put("beginTime", df.format(df.parse(beginTime + " 00:01:01")));
		params.put("endTime", df.format(df.parse(endTime + " 23:59:59")));
		params.put("orgId", orgId);
		params.put("gradeId", gradeId);
		params.put("projectKind", projectKind);
		params.put("modelType", modelType);
		
		List<JumpClassSummaryDto> summaryList = null;
		
		try{
			summaryList = statisticsService.queryTrainClassSummaryList(params);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		
		List<ClassInfoDto> classes = getClassInfoList(orgId, gradeId);
		
		Map<String, Object> result = new HashMap<>();
		result.put("classNames", buildClassNames(summaryList, classes));
		result.put("classLineGraph", buildClassLineGraph(summaryList));
		return new ResultDTO<>(result);
	}

	private List<ClassInfoDto> getClassInfoList(Long orgId, Long gradeId){
		
		ResultDTO<List<GradeTreeDto>> result = basicFeignService.getClassTree(orgId);
		List<GradeTreeDto> grades = result.getData();
		for(GradeTreeDto dto : grades) {
			if(dto.getGradeId() == gradeId) {
				return dto.getClassInfoList();
			}
		}
		return null;
	}
	
	private List<ProjectClassLineGraphDto> buildClassLineGraph(List<JumpClassSummaryDto> summaryList) {
		ProjectClassLineGraphDto male = new ProjectClassLineGraphDto(1, "男");
		ProjectClassLineGraphDto female = new ProjectClassLineGraphDto(2, "女");
		ProjectClassLineGraphDto total = new ProjectClassLineGraphDto(3, "总体");
		for(JumpClassSummaryDto summary : summaryList) {
			male.addData(summary.getMaleAvgCount());
			female.addData(summary.getFemaleAvgCount());
			total.addData(summary.getAvgCount());
		}
		List<ProjectClassLineGraphDto> list = new ArrayList<>();
		list.add(male);
		list.add(female);
		list.add(total);
		return list;
	}

	private List<String> buildClassNames(List<JumpClassSummaryDto> summaryList, List<ClassInfoDto> classes) {
		List<String> classNames = new ArrayList<>();
		for(JumpClassSummaryDto summary : summaryList) {
			long classId = summary.getClassId();
			for(ClassInfoDto dto : classes) {
				if(dto.getId() == classId) {
					classNames.add(dto.getClassName());
					break;
				}
			}
		}
		return classNames;
	}

	@ApiOperation(value = "获取学校年级项目列表")
	@RequestMapping(value = "/queryProjectTrainList4PC", method = RequestMethod.GET)
	public ResultDTO<?> queryProjectTrainList4PC(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "项目类型", required = false) @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "模式", required = false) @RequestParam(name = "modelType", required = false) Byte modelType,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "startTime", required = false) String beginTime,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endTime", required = false) String endTime,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize)throws Exception{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, Object> params = new HashMap<>();
		params.put("beginTime", df.format(df.parse(beginTime + " 00:01:01")));
		params.put("endTime", df.format(df.parse(endTime + " 23:59:59")));
		params.put("orgId", orgId);
		params.put("classId", classId);
		params.put("projectKind", projectKind);
		params.put("modelType", modelType);
		PageInfo<JumpTrainSummaryDto> summaryList = statisticsService.queryTrainSummaryList4PC(params, pageNo, pageSize);
		return new ResultDTO<>(summaryList);
	}

	@ApiOperation(value = "协调及速度详细")
	@RequestMapping(value = "/getProjectDetailPage", method = RequestMethod.GET)
	public ResultDTO<?> getProjectDetailPage(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "训练ID", required = true) @RequestParam(name = "trainId", required = true) Long trainId)throws Exception{
		
		Map<String, Object> params = new HashMap<>();
		params.put("trainId", trainId);
		JumpTrainSummaryDto dto = statisticsService.getTrain(params);
		
//		ResultDTO<List<StudentInfoDto>> resultDto = basicFeignService.getStudentInfoListByClassId(orgId, dto.getClassId());
//
//		if(resultDto != null && resultDto.getData() != null) {
//			studentCount = resultDto.getData().size();
//		}
		int studentCount = basicMapper.getClassCount(dto.getClassId());
		Map<String, Object> result = new HashMap<>();
		result.put("descriptions", buildTrainDescriptions(dto));
		result.put("pieGraph", buildPieGraph(dto));
		result.put("barGraph", buildBarGraph(dto));
		result.put("detail", dto);
		result.put("studentCount", studentCount);
		return new ResultDTO<>(result);
	}

	private List<ProjectTrainDescriptionDto> buildTrainDescriptions(JumpTrainSummaryDto dto) {
		ProjectTrainDescriptionDto fine = new ProjectTrainDescriptionDto(3, "优秀", "#0FDD8D");
		ProjectTrainDescriptionDto good = new ProjectTrainDescriptionDto(2, "良好", "#62F0FB");
		ProjectTrainDescriptionDto pass = new ProjectTrainDescriptionDto(1, "及格", "#FFD02E");

		fine.setNan(dto.getMaleFine());
		fine.setNv(dto.getFemaleFine());
		good.setNan(dto.getMaleGood());
		good.setNv(dto.getFemaleGood());
		pass.setNan(dto.getMalePass());
		pass.setNv(dto.getFemalePass());
		int total = dto.getFemale() + dto.getMale();
		
		fine.buildNum(total);
		good.buildNum(total);
		pass.buildNum(total);
		List<ProjectTrainDescriptionDto> list = new ArrayList<>();
		list.add(fine);
		list.add(good);
		list.add(pass);
		return list;
	}

	private List<ProjectTrainPieGraph> buildPieGraph(JumpTrainSummaryDto dto) {

		ProjectTrainPieGraph fine = new ProjectTrainPieGraph(3, "优秀");
		ProjectTrainPieGraph good = new ProjectTrainPieGraph(2, "良好");
		ProjectTrainPieGraph pass = new ProjectTrainPieGraph(1, "及格");

		fine.setValue(dto.getMaleFine() + dto.getFemaleFine());
		good.setValue(dto.getMaleGood() + dto.getFemaleGood());
		pass.setValue(dto.getMalePass() + dto.getFemalePass());

		List<ProjectTrainPieGraph> list = new ArrayList<>();
		list.add(fine);
		list.add(good);
		list.add(pass);
		return list;
	}

	private List<ProjectGradeBarGraph> buildBarGraph(JumpTrainSummaryDto dto) {
		ProjectGradeBarGraph male = new ProjectGradeBarGraph(1, "男");
		ProjectGradeBarGraph female = new ProjectGradeBarGraph(2, "女");
		
		male.addData(dto.getMaleFine());
		male.addData(dto.getMaleGood());
		male.addData(dto.getMalePass());
		male.addData(dto.getMaleFail());

		female.addData(dto.getFemaleFine());
		female.addData(dto.getFemaleGood());
		female.addData(dto.getFemalePass());
		female.addData(dto.getFemaleFail());
		
		List<ProjectGradeBarGraph> list = new ArrayList<>();
		list.add(male);
		list.add(female);
		return list;
	}
	
	@ApiOperation(value = "训练个人详细")
	@RequestMapping(value = "/getStudentDetailPage", method = RequestMethod.GET)
	public ResultDTO<?> getStudentDetailPage(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "学号", required = false) @RequestParam(name = "studentNo", required = false) String studentNo,
			@ApiParam(value = "开始时间(yyyy-MM-dd)", required = false) @RequestParam(name = "startTime", required = false) String beginTime,
			@ApiParam(value = "结束时间(yyyy-MM-dd)", required = false) @RequestParam(name = "endTime", required = false) String endTime)throws Exception{
		SimpleDateFormat dfParse = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
		Map<String, Object> result = new HashMap<>();
		
		ResultDTO<StudentInfoDto> res = basicFeignService.getStudentByStudentNo(orgId,null,null, studentNo);
		
		StudentInfoDto studentInfoDto = res.getData();
		
		result.put("headImg", studentInfoDto.getHeadImgUrl());
		result.put("studentName", studentInfoDto.getName());
		result.put("sex", "男".equals(studentInfoDto.getSex()) ? 1 : 2);
		result.put("className", studentInfoDto.getClassName());
		result.put("studentId", studentInfoDto.getId());
		result.put("studentNo", studentNo);
		if(studentInfoDto.getBirthDate() != null) {
			long time = System.currentTimeMillis() - studentInfoDto.getBirthDate().getTime();
			long yearOld = time / (1000 * 60 * 60 * 24 * 365);
			result.put("yearOld", yearOld);
		}
		result.put("term", df.format(dfParse.parse(beginTime)) + " - " + df.format(dfParse.parse(endTime)));
		
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("studentNo", studentNo);
		params.put("beginTime", beginTime + " 00:01:01");
		params.put("endTime", endTime + " 23:59:59");
		Double avgScore;
		try{
			avgScore = trainService.queryTrainStudentSummary(params);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		String score = "0.00";
		if(avgScore != null) {
			NumberFormat nf = NumberFormat.getNumberInstance();
			nf.setMaximumFractionDigits(2);
			score = nf.format(avgScore);
		}
		result.put("avgScore", score);
		
		return new ResultDTO<>(result);
	}

	private void logError(Throwable e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		pw.flush();
		log.error(sw.toString());
		
	}
}
